package com.we.flink.dcapiuserlabel.table;

import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.util.Collector;

import com.alibaba.fastjson.JSONObject;

public class TableDcStatusRecord {
    public static final String KFKTABLE = "fdm.hhl01_dc_status_record";
    public static final String QUERYSQL =
            "select uid, status as dc_api_status,"
                    + " ifnull(updated_at,0) as updated_at from "
                    + KFKTABLE
                    + " where deleted_at is null ";

    public long uid;
    public int dc_api_status;
    public int updated_at;

    public TableDcStatusRecord() {}

    public TableDcStatusRecord(long uid, int status, int updated_at) {
        this.uid = uid;
        this.updated_at = updated_at;
        this.dc_api_status = status;
    }

    public static TableDcStatusRecord init(long uid) {
        return new TableDcStatusRecord(uid, 0, 0);
    }

    public static SingleOutputStreamOperator<String> getFlatMapStream(
            StreamTableEnvironment tableEnv, StreamExecutionEnvironment env) {
        Table tableRes = tableEnv.sqlQuery(TableDcStatusRecord.QUERYSQL);
        DataStream<Tuple2<Boolean, TableDcStatusRecord>> inputStream =
                tableEnv.toRetractStream(tableRes, TableDcStatusRecord.class);

        SingleOutputStreamOperator<String> out =
                inputStream
                        .filter(
                                new FilterFunction<Tuple2<Boolean, TableDcStatusRecord>>() {
                                    @Override
                                    public boolean filter(
                                            Tuple2<Boolean, TableDcStatusRecord> value)
                                            throws Exception {
                                        return value.f0;
                                    }
                                })
                        .uid("TagDcStatusRecord-filter")
                        .keyBy(
                                new KeySelector<Tuple2<Boolean, TableDcStatusRecord>, Long>() {
                                    @Override
                                    public Long getKey(Tuple2<Boolean, TableDcStatusRecord> value)
                                            throws Exception {
                                        return value.f1.getUid();
                                    }
                                })
                        .flatMap(
                                new RichFlatMapFunction<
                                        Tuple2<Boolean, TableDcStatusRecord>, String>() {
                                    ValueState<TableDcStatusRecord> dcStatusRecordVState;

                                    @Override
                                    public void open(Configuration parameters) throws Exception {
                                        dcStatusRecordVState =
                                                getRuntimeContext()
                                                        .getState(
                                                                new ValueStateDescriptor<
                                                                        TableDcStatusRecord>(
                                                                        "DcStatusRecordVState",
                                                                        TableDcStatusRecord.class));
                                    }

                                    @Override
                                    public void flatMap(
                                            Tuple2<Boolean, TableDcStatusRecord> value,
                                            Collector<String> out)
                                            throws Exception {
                                        long uid = value.f1.getUid();
                                        int updated_at = value.f1.getUpdated_at();
                                        int dc_api_status = value.f1.getDc_api_status();

                                        TableDcStatusRecord tmpState = dcStatusRecordVState.value();
                                        TableDcStatusRecord curState =
                                                tmpState == null
                                                        ? TableDcStatusRecord.init(uid)
                                                        : tmpState;

                                        if (updated_at > curState.getUpdated_at()) {
                                            if (dc_api_status != curState.getDc_api_status()) {
                                                JSONObject jsonObject = new JSONObject();
                                                jsonObject.put("uid", uid);
                                                jsonObject.put("dc_api_status", dc_api_status);
                                                out.collect(jsonObject.toString());

                                                curState.dc_api_status = dc_api_status;
                                                curState.updated_at = updated_at;
                                                dcStatusRecordVState.update(curState);
                                            }
                                        }
                                    }
                                });

        return out;
    }

    public long getUid() {
        return uid;
    }

    public int getDc_api_status() {
        return dc_api_status;
    }

    public int getUpdated_at() {
        return updated_at;
    }
}
